import React, { useRef, useEffect, Suspense, useState } from 'react';
import { Canvas, useFrame, useLoader } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { TextureLoader } from 'three';
import { useUserStore } from '../../store/userStore';
import * as THREE from 'three';
// import { PlanetEcoPanel } from './PlanetEcoPanel';

interface PlanetMeshProps {
  energyRatio: number;
}

const textureLoader = new TextureLoader();
const earthTexturePromise = textureLoader.loadAsync('/textures/earth_day.jpg');
const cloudsTexturePromise = textureLoader.loadAsync('/textures/earth_clouds.png');

const LOW_DETAIL: [number, number, number] = [1, 16, 16];
const HIGH_DETAIL: [number, number, number] = [1, 64, 64];

const PlanetMesh: React.FC<PlanetMeshProps> = ({ energyRatio }) => {
  const planetRef = useRef<THREE.Mesh>(null);
  const cloudsRef = useRef<THREE.Mesh>(null);
  const [detail, setDetail] = useState(LOW_DETAIL);
  const [earthTexture, setEarthTexture] = useState<THREE.Texture | null>(null);
  const [cloudsTexture, setCloudsTexture] = useState<THREE.Texture | null>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    Promise.all([earthTexturePromise, cloudsTexturePromise])
      .then(([earth, clouds]) => {
        setEarthTexture(earth);
        setCloudsTexture(clouds);
        setLoaded(true);
        
        setTimeout(() => setDetail(HIGH_DETAIL), 1000);
      })
      .catch(error => console.error('Failed to load textures:', error));
  }, []);

  const dayIntensity = Math.max(0.3, energyRatio);
  const cloudOpacity = Math.min(0.5, 0.1 + energyRatio * 0.4);

  useEffect(() => {
    if (!loaded) return;
    
    if (planetRef.current && planetRef.current.material) {
      (planetRef.current.material as THREE.MeshStandardMaterial).emissiveIntensity = dayIntensity;
    }
    if (cloudsRef.current && cloudsRef.current.material) {
      (cloudsRef.current.material as THREE.MeshPhongMaterial).opacity = cloudOpacity;
    }
  }, [dayIntensity, cloudOpacity, loaded]);

  useFrame(({ clock }) => {
    if (!loaded) return;
    
    const time = clock.getElapsedTime();
    
    if (cloudsRef.current) {
      cloudsRef.current.rotation.y = time * 0.03;
    }
  });

  if (!earthTexture || !cloudsTexture) {
    return (
      <mesh>
        <sphereGeometry args={LOW_DETAIL} />
        <meshBasicMaterial color="#1a5276" />
      </mesh>
    );
  }

  return (
    <group>
      <mesh ref={planetRef} castShadow receiveShadow>
        <sphereGeometry args={[detail[0], detail[1], detail[2]]} />
        <meshStandardMaterial 
          map={earthTexture} 
          emissive="#ffffff"
          emissiveIntensity={dayIntensity}
        />
      </mesh>

      <mesh ref={cloudsRef} scale={1.01}>
        <sphereGeometry args={[detail[0], Math.max(16, Math.floor(detail[1]/2)), Math.max(16, Math.floor(detail[2]/2))]} />
        <meshPhongMaterial
          map={cloudsTexture}
          transparent={true}
          opacity={cloudOpacity}
          depthWrite={false}
          blending={THREE.AdditiveBlending}
        />
      </mesh>
    </group>
  );
};

const PlanetWithSuspense = ({ energyRatio }: PlanetMeshProps) => (
  <Suspense fallback={
    <div style={{
      width: '100%',
      height: '100%',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      color: '#1a5276',
      background: '#f0f0f0',
      borderRadius: '8px'
    }}>
      加载星球中...
    </div>
  }>
    <PlanetMesh energyRatio={energyRatio} />
  </Suspense>
);

export const Planet: React.FC = () => {
  const { user } = useUserStore();
  const [loaded, setLoaded] = useState(false);
  
  const energyRatio = user?.planetState.energy 
    ? user.planetState.energy.clean / user.planetState.energy.total 
    : 0.5;

  useEffect(() => {
    const handleSourceMapError = (event: ErrorEvent) => {
      if (event.message.includes('vision_bundle_mjs.js.map')) {
        console.warn('Failed to load source map:', event.message);
        event.preventDefault();
      }
    };

    window.addEventListener('error', handleSourceMapError);
    
    const timer = setTimeout(() => setLoaded(true), 100);

    return () => {
      window.removeEventListener('error', handleSourceMapError);
      clearTimeout(timer);
    };
  }, []);
  
  return (
    <div style={{ width: '100%', height: 'calc(100vh - 40px)' }}>
      {/* {loaded && (
        <PlanetEcoPanel
          pollution={user?.planetState.pollution || 0}
          biodiversity={user?.planetState.biodiversity || 0}
          trees={user?.planetState.trees || 0}
          waterQuality={user?.planetState.waterQuality || 0}
          greenEnergy={energyRatio}
        />
      )} */}
      
      <Canvas
        camera={{ position: [0, 2, 4], fov: 45 }}
        shadows={false}
        dpr={[1, 1.5]}
      >
        <color attach="background" args={['#000']} />
        <ambientLight intensity={0.5} />
        <directionalLight
          position={[5, 3, 5]}
          intensity={1}
          castShadow={false}
        />
        <PlanetWithSuspense energyRatio={energyRatio} />
        <OrbitControls
          enablePan={false}
          enableZoom={true}
          minDistance={2.5}
          maxDistance={5}
          minPolarAngle={Math.PI / 4}
          maxPolarAngle={Math.PI / 1.5}
        />
      </Canvas>
    </div>
  );
};